/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package jmediaplayer;

import com.almworks.sqlite4java.SQLiteConnection;
import com.almworks.sqlite4java.SQLiteException;
import com.almworks.sqlite4java.SQLiteStatement;
import java.io.File;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
import java.util.logging.Level;
import java.util.logging.Logger;

/**
 *
 * @author dean.williams
 */
public class setting {

	static int fullscreen = 1;
	static String storeDirectory = "Store\\";
	static HashMap<String,String> settings = new HashMap<String,String>();
	static HashMap<String,String> defaultSettings = new HashMap<String,String>();
	static SQLiteConnection dbS;

	public setting() {
		dbS = new SQLiteConnection(new File(storeDirectory + "Settings.db"));

		try {
			dbS.open(true);

			//If it doesnt exist create the table
			dbS.exec("create table if not exists settings (id INTEGER NOT NULL PRIMARY KEY,"
					+ " name TEXT  NULL,"
					+ " value TEXT  NULL)");

			//read the rows
			SQLiteStatement st = dbS.prepare("SELECT * FROM settings");

			//loop through the results
			while (st.step()) {
				settings.put(st.columnString(1), st.columnString(2));
				System.out.println("Setting: " + st.columnString(1) + "=" + st.columnString(2));
			}

			//dispose the data
			st.dispose();
		} catch (SQLiteException ex) {
			Logger.getLogger(setting.class.getName()).log(Level.SEVERE, null, ex);
		}

		//Default settings
		defaultSettings.put("fullscreen","1");
		defaultSettings.put("mediaDirectory","Media\\");
		defaultSettings.put("allowDuplicates","true");
		defaultSettings.put("tempDirectory",storeDirectory + "Temp\\");
		defaultSettings.put("iconCacheDirectory",storeDirectory + "IconCache\\");

		//Iterator for checking DB
		Iterator iter = defaultSettings.entrySet().iterator();

		while (iter.hasNext()) {
			Map.Entry mEntry = (Map.Entry) iter.next();
			String key = mEntry.getKey().toString();
			String val = mEntry.getValue().toString();


			if (settings.containsKey(key) == false) {
				//Well lets load out the default and drop the default into the DB :D
				settings.put(key, val);

				try {
					//TODO: Make this query safe!
					dbS.exec("INSERT INTO settings (name,value) VALUES ('" + key + "','" + val + "')");
				} catch (SQLiteException ex) {
					Logger.getLogger(setting.class.getName()).log(Level.SEVERE, null, ex);
				}
			}
		}

		//The Store directory is required AS-IS for now, dont really need to change this ever.
		defaultSettings.put("storeDirectory", storeDirectory);
		settings.put("storeDirectory", storeDirectory);

		//now we have the settings, we may need to setup some tables :)
		try {
			//Setup the SQLite DB
			SQLiteConnection dbMS = new SQLiteConnection(new File(settings.get("storeDirectory") + "MediaStore.db"));
			dbMS.open(true);
			dbMS.exec("create table if not exists files (id INTEGER NOT NULL PRIMARY KEY,"
					+ " hash TEXT  NULL,"
					+ " base TEXT  NULL,"
					+ " location TEXT  NULL,"
					+ " filename TEXT  NULL,"
					+ " name TEXT  NULL,"
					+ " description TEXT  NULL,"
					+ " imageSmll TEXT  NULL,"
					+ " imageLrge TEXT  NULL,"
					+ " episodeName TEXT  NULL,"
					+ " episodes INTEGER DEFAULT '1' NULL,"
					+ " episode INTEGER DEFAULT '1' NULL,"
					+ " categories TEXT  NULL,"
					+ " genres TEXT  NULL,"
					+ " tags TEXT  NULL,"
					+ " rating INTEGER DEFAULT '0' NULL)");
			dbMS.dispose();
		} catch (SQLiteException ex) {
			Logger.getLogger(FormMain.class.getName()).log(Level.SEVERE, null, ex);
		}

		//Close the DB
		dbS.dispose();
	}

	public static String get(String key) {
		//Well lets make sure were not accessing something missing.
		String val = "";

		if (settings.containsKey(key)) {
			val = settings.get(key);
		} else {
			System.out.println("Error: Get setting '" + key + "' doesn't exist!");
		}

		return val;
	}

	public static int getI(String key) {
		//Well lets make sure were not accessing something missing.
		String val = "";

		if (settings.containsKey(key)) {
			val = settings.get(key);
		} else {
			System.out.println("Error: Get setting '" + key + "' doesn't exist!");
		}

		return Integer.parseInt(val);
	}

	public static boolean getB(String key) {
		//Well lets make sure were not accessing something missing.
		String val = "";

		if (settings.containsKey(key)) {
			val = settings.get(key);
		} else {
			System.out.println("Error: Get setting '" + key + "' doesn't exist!");
		}

		return (val.compareTo("true") == 0 ? true : false);
	}

	public static void set(String key, String val) {
		settings.put(key, val);

		//Check if we have a default setting...
		if (defaultSettings.containsKey(key) == false) {
			System.out.println("Warning: New setting '" + key + "' doesn't exist in defaults!");
		} else {
			try {
				dbS = new SQLiteConnection(new File(storeDirectory + "Settings.db"));
				dbS.open();

				//TODO: Make this secure.
				dbS.exec("UPDATE settings SET value = '" + val + "' WHERE name = '" + key + "'");

				//Close the DB
				dbS.dispose();
			} catch (SQLiteException ex) {
				Logger.getLogger(FormSettings.class.getName()).log(Level.SEVERE, null, ex);
			}
		}
	}

	public static void setI(String key, int val) {
		set(key,String.valueOf(val));
	}

	public static void setB(String key, boolean val) {
		set(key,String.valueOf(val));
	}

	//Returns 1 if done and 0 if failed
	public static int reset(String key) {
		//Check if we have a default setting...
		int done = 0;

		if (defaultSettings.containsKey(key)) {
			settings.put(key, defaultSettings.get(key).toString());
			done = 1;
		} else {
			System.out.println("Error: Resetting '" + key + "' to default has failed because it doesn't exist in defaults!");
		}

		return done;
	}

	public static HashMap<String,String> settings() {
		return settings;
	}
}
